package ltd.newbee.mall.api.admin;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiParam;
import ltd.newbee.mall.api.admin.dto.AdminPermDto;
import ltd.newbee.mall.api.admin.param.QueryAdminPermParam;
import ltd.newbee.mall.api.admin.vo.AdminPermVo;
import ltd.newbee.mall.entity.AdminPerm;
import ltd.newbee.mall.service.AdminPermService;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import ltd.newbee.mall.valid.UpdateValid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = {"/manage-api/v1"})
@Api(tags = {"权限菜单"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class AdminPermAPI {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminPermAPI.class);

    @Resource
    private AdminPermService adminPermService;

    @ApiParam(value = "查询")
    @GetMapping(value = { "/perm/list" })
    public Result<?> list(QueryAdminPermParam param) {
        Page<AdminPermVo> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<AdminPermVo> data = adminPermService.selectPageByCondition(page, param);
        page.setRecords(data);
        return ResultGenerator.genSuccessResult(page);
    }

    @ApiParam(value = "新增")
    @PostMapping(value = "/perm")
    public Result add(@RequestBody @Validated AdminPermDto dto) {
        LOGGER.info("开始新增 add -> {}", dto);
        AdminPerm perm = BeanUtil.copyProperties(dto, AdminPerm.class, "id");
        adminPermService.save(perm);
        return ResultGenerator.genSuccessResult();
    }

    @ApiParam(value = "更新")
    @PutMapping(value = "/perm/{id}")
    public Result update(@PathVariable(name = "id") Long id , @RequestBody @Validated(value = { UpdateValid.class }) AdminPermDto dto) {
        LOGGER.info("开始编辑 update -> {} ", dto);
        AdminPerm perm = BeanUtil.copyProperties(dto, AdminPerm.class);
        UpdateWrapper<AdminPerm> update = new UpdateWrapper<>();
        update.eq("id", id);
        adminPermService.update(perm, update);
        return ResultGenerator.genSuccessResult();
    }
}
